#include "paneltag.h"
#include "main.h"
#include "dlgedittag.h"
#include "pmclientdata.h"
#include "pm/manager.h"
#include <boost/foreach.hpp>

PanelTag::PanelTag(wxWindow* parent)
: PanelTagGui(parent)
{
	wxTheApp->Connect(pmEVT_PROJECT_LOADED, wxCommandEventHandler(PanelTag::OnProjectLoaded), NULL, this);
	
	pmConnect(pmEVT_TAG_REMOVED, db::ID,    PanelTag::OnTagRemoved);
}

void PanelTag::AddTag(const pm::Tag& tag)
{
	int i = m_listTag->Append(wxEmptyString);
	m_listTag->SetClientObject(i, new IdClientData(tag.id()));
	SetTag(i, tag);
}

void PanelTag::SetTag(int i, const pm::Tag& tag)
{
	m_listTag->SetString(i, tag.name());
}

void PanelTag::OnProjectLoaded(wxCommandEvent& event)
{
	event.Skip();
	
	m_listTag->Clear();
	
	pm::ListTag tags;
	pm::select_all(tags);
	BOOST_FOREACH (const pm::Tag& tag, tags) {
		AddTag(tag);
	}
}

void PanelTag::OnTagRemoved(pmEvent<db::ID>& event)
{
	event.Skip();
	
}

void PanelTag::OnAddTag( wxCommandEvent& WXUNUSED(event) )
{
	DlgNewTag dlg(this);
	if (dlg.ShowModal() == wxID_OK) {
		AddTag(dlg.GetTag());
	}
}

void PanelTag::OnDelTag( wxCommandEvent& event )
{
	
}

void PanelTag::OnTagActivated( wxCommandEvent& event )
{
	int sel = event.GetSelection();
	db::ID id = dynamic_cast<IdClientData*>(m_listTag->GetClientObject(sel))->id();
	pm::Tag tag;
	pm::get_by_id(id, tag);
	DlgUpdateTag dlg(this, tag);
	if (dlg.ShowModal() == wxID_OK) {
		SetTag(sel, dlg.GetTag());
	}
}
